package com.ruoyi.web.controller.user;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.AliyunOssUploadUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.framework.security.context.LoginContext;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.user.VsDramasUserOauth;
import com.ruoyi.system.service.user.IVsDramasUserOauthService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.domain.model.VsUser;
import com.ruoyi.system.service.user.IVsUserService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
/**
 * This file is part of 南阳迈特网络科技有限公司.
 * @company  南阳迈特网络科技有限公司
 * @link     https://www.nymaite.com
 * @document https://product.nymaite.cn
 * @contact  service@nymaite.com
 * @author nymaite
 */
/**
 * 会员Controller
 * 
 * @author zzx
 * @date 2024-04-30
 */
@Api(tags = "会员")
@RestController
@RequestMapping("/user/user")
public class VsUserController extends BaseController
{
    @Autowired
    private IVsUserService vsUserService;

    @Autowired
    private LoginContext loginContext;

    @Resource
    @Qualifier("VsUserAuthenticationManager")
    private AuthenticationManager authenticationManager;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IVsDramasUserOauthService vsDramasUserOauthService;

    /**
     * 查询会员列表
     */
//    @ApiOperation("查询会员列表")
//    @ApiImplicitParams(value = {
//            @ApiImplicitParam(name = "langId", value = "langId", required=true),
//            @ApiImplicitParam(name = "pageNum", value = "页数", required=true),
//            @ApiImplicitParam(name = "pageSize", value = "数量", required=true)
//    })
    @GetMapping("/list")
    public TableDataInfo list(VsUser vsUser)
    {
        startPage();
        List<VsUser> list = vsUserService.selectVsUserList(vsUser);
        return getDataTable(list);
    }

    /**
     * 导出会员列表
     */
//    @ApiOperation("导出会员列表")
    @Log(title = "会员", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, VsUser vsUser)
    {
        List<VsUser> list = vsUserService.selectVsUserList(vsUser);
        ExcelUtil<VsUser> util = new ExcelUtil<VsUser>(VsUser.class);
        util.exportExcel(response, list, "会员数据");
    }

    /**
     * 获取会员详细信息
     */
    @ApiOperation("获取会员详细信息")
    @ApiImplicitParam(name = "id", value = "id", required=true)
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(vsUserService.selectVsUserById(id));
    }

    /**
     * 新增会员
     */
//    @ApiOperation("新增会员")
    @Log(title = "会员", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody VsUser vsUser)
    {
        return toAjax(vsUserService.insertVsUser(vsUser));
    }

    /**
     * 修改会员
     */
//    @ApiOperation("修改会员")
    @Log(title = "会员", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody VsUser vsUser)
    {
        return toAjax(vsUserService.updateVsUser(vsUser));
    }

    /**
     * 删除会员
     */
//    @ApiOperation("删除会员")
    @Log(title = "会员", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(vsUserService.deleteVsUserByIds(ids));
    }

    @ApiOperation("密码登录")
    @PostMapping("/mobilepwdLogin")
    public AjaxResult mobileCodeLogin(@RequestBody VsUser vsUser)
    {
//        if (StringUtils.isEmpty(vsUser.getAreaCode())) {
//            return error("国际区号不能为空！");
//        }
        if (StringUtils.isEmpty(vsUser.getKeyword())) {
            return error("手机号或邮箱不能为空！");
        }
        if (StringUtils.isEmpty(vsUser.getPassword())) {
            return error("密码不能为空！");
        }
        Map map = vsUserService.login(vsUser);
        return AjaxResult.success(map);
    }

    @ApiOperation("发送短信或邮箱")
    @PostMapping("/sendCode")
    public AjaxResult sendCode(@RequestBody VsUser vsUser, HttpServletRequest request) {
        if (StringUtils.isEmpty(vsUser.getKeyword())) {
            return error("手机号或邮箱不能为空！");
        }
        if (vsUser.getIsRegister() != null) {
            VsUser user = vsUserService.selectVsUserInfo(vsUser);
            if (!StringUtils.isNull(user)) {
                return error("禁止重复注册！");
            }
        }
        String regex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(vsUser.getKeyword());
        // 如果是邮箱就发邮箱验证码，否则为短信验证码
        String s;
        if (matcher.matches()) {
            s = vsUserService.sendEmail(vsUser.getKeyword(), request.getHeader("Lang-Id"));
        } else {
            if (StringUtils.isEmpty(vsUser.getAreaCode())) {
                return error("国际区号不能为空！");
            }
            s = vsUserService.sendPhone(vsUser.getAreaCode(), vsUser.getKeyword(), request.getHeader("Lang-Id"));
        }
        if ("success".equals(s)) {
            return success("验证码发送成功！");
        } else {
            return error("验证码发送失败！");
        }

    }

    @ApiOperation("验证码登录")
    @PostMapping("/codeLogin")
    public AjaxResult emsOrSmsLogin(@RequestBody VsUser vsUser, HttpServletRequest request) {
//        if (StringUtils.isEmpty(vsUser.getAreaCode())) {
//            return error("国际区号不能为空！");
//        }
        if (StringUtils.isEmpty(vsUser.getKeyword())) {
            return error("手机号或邮箱不能为空！");
        }
        if (StringUtils.isEmpty(vsUser.getCode())) {
            return error("验证码不能为空！");
        }
        // 先去查询用户是否存在，如果不存在先注册，存在就直接去校验验证码
        VsUser user = vsUserService.selectVsUserInfo(vsUser);
        if (StringUtils.isNull(user)) {
            user = vsUserService.registerUser(vsUser,request.getHeader("Lang-Id"));
        }
        vsUserService.checkCode(vsUser.getKeyword(), vsUser.getCode());
        if (!StringUtils.isNull(user)) {
            Map map = vsUserService.smsLogin(user);
            return success(map);
        } else {
            return error("注册失败，请联系管理员！");
        }
    }

    @PostMapping("/registerUser")
    public AjaxResult registerUser(@RequestBody VsUser vsUser, HttpServletRequest request) {
        if (vsUser != null) {
            if (vsUser.getOpenid() == null && "".equals(vsUser.getOpenid())) {
                VsUser user = vsUserService.selectVsUserInfo(vsUser);
                if (!StringUtils.isNull(user)) {
                    return error("该用户已注册！");
                }
            }
        }
        VsUser aBoolean = vsUserService.registerUser(vsUser,request.getHeader("Lang-Id"));
        if (vsUser != null && vsUser.getOpenid() != null && !"".equals(vsUser.getOpenid())) {
            Map map = vsUserService.smsLogin(aBoolean);
            return success(map);
        }
        vsUserService.checkCode(vsUser.getKeyword(), vsUser.getCode());
        if (!StringUtils.isNull(aBoolean)) {
            Map map = vsUserService.smsLogin(vsUser);
            return success(map);
        } else {
            return error("注册失败！");
        }
    }

    @PostMapping("/editPassword")
    public AjaxResult editPwd(@RequestBody VsUser vsUser) {
        if (getLoginUser().getVsUser() == null) {
            return error("暂未登录！");
        }
        vsUserService.checkCode(vsUser.getKeyword(), vsUser.getCode());
        return success(vsUserService.editPwd(vsUser));
    }

    @PostMapping("/forgotPassword")
    public AjaxResult forgotPassword(@RequestBody VsUser vsUser) {
        vsUserService.checkCode(vsUser.getKeyword(), vsUser.getCode());
        Boolean aBoolean = vsUserService.forgotPassword(vsUser);
        if (aBoolean) {
            return success();
        }
        return error();
    }

    @PostMapping("/parentList")
    public TableDataInfo parentList(@RequestBody VsUser vsUser)
    {
        startPage();
        List<VsUser> list = vsUserService.selectParentList(vsUser);
        return getDataTable(list);
    }

    /**
     * 头像上传
     */
    @CrossOrigin
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws Exception
    {
        if (getLoginUser().getVsUser() == null) {
            return error("暂未登录！");
        }
        if (!file.isEmpty())
        {
            LoginUser loginUser = getLoginUser();
            String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
//            String avatar = AliyunOssUploadUtils.uploadFile(file);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", avatar);
            ajax.put("fileName", FileUtils.getName(avatar));
            ajax.put("newFileName", FileUtils.getName(avatar));
            ajax.put("originalFilename", file.getOriginalFilename());
            if (vsUserService.updateUserAvatar(loginUser.getVsUser().getId(), avatar))
            {
                ajax.put("imgUrl", avatar);
                // 更新缓存用户头像
                loginUser.getVsUser().setAvatar(avatar);
                tokenService.setLoginUser(loginUser);
                return ajax;
            }
        }
        return error("上传图片异常，请联系管理员");
    }

    @PostMapping("/updateNickName")
    public AjaxResult updateNickName(@RequestBody VsUser vsUser) {
        if (getLoginUser().getVsUser() == null) {
            return error("暂未登录！");
        }
        VsUser user = getLoginUser().getVsUser();
        vsUser.setId(user.getId());
        int i = vsUserService.updateVsUser(vsUser);
        if (i == 0) {
            return error();
        }
        LoginUser loginUser = getLoginUser();
        AjaxResult ajax = AjaxResult.success();
        ajax.put("nickname", vsUser.getNickname());
        // 更新缓存用户头像
        loginUser.getVsUser().setNickname(vsUser.getNickname());
        tokenService.setLoginUser(loginUser);
        return ajax;
    }

    @PostMapping("/updateEmailOrPhone")
    public AjaxResult updateEmailOrPhone(@RequestBody VsUser vsUser) {
        if (getLoginUser().getVsUser() == null) {
            return error("暂未登录！");
        }
        vsUserService.checkCode(vsUser.getKeyword(), vsUser.getCode());
        VsUser userInfo = getLoginUser().getVsUser();
        VsUser editUser = new VsUser();
        editUser.setId(userInfo.getId());
        String regex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(vsUser.getKeyword());

        // 更新缓存用户信息
        String s;
        if (matcher.matches()) {
            s = "email";
            editUser.setEmail(vsUser.getKeyword());
        } else {
            s = "mobile";
            editUser.setMobile(vsUser.getKeyword());
        }
        int i = vsUserService.updateVsUser(editUser);
        if (i == 0) {
            return error();
        }
        LoginUser loginUser = getLoginUser();
        if ("email".equals(s)) {
            loginUser.getVsUser().setEmail(vsUser.getKeyword());
        } else {
            loginUser.getVsUser().setMobile(vsUser.getKeyword());
        }
        tokenService.setLoginUser(loginUser);
        return success();
    }

    @PostMapping("/rechargeUserUsable")
    public AjaxResult rechargeUserUsable(@RequestBody VsUser vsUser) {
        return success(vsUserService.updateVsUserUsable(vsUser));
    }

    @PostMapping("/selectVsUserByInfo")
    public AjaxResult selectVsUserByInfo(@RequestBody VsUser vsUser) {
        return success(vsUserService.selectVsUserByInfo(vsUser));
    }

    @PostMapping("/rechargeUserMoney")
    public AjaxResult rechargeUserMoney(@RequestBody VsUser vsUser) {
        return success(vsUserService.updateVsUserMoney(vsUser));
    }

    @PostMapping("/setParent")
    public AjaxResult setUpParent(@RequestBody VsUser vsUser) {
        if (getLoginUser().getVsUser() == null) {
            return error("暂未登录！");
        }
        if (getLoginUser().getVsUser().getId() == vsUser.getId()) {
            return error("Cannot bind oneself");
        }
        if (vsUser.getId() == 1 || vsUser.getId() == 0) {
            return error("The superior does not exist");
        }
        if (getLoginUser().getVsUser().getParentUserId() == null) {
            VsUser parentUser = vsUserService.selectVsUserById(vsUser.getId());
            if (parentUser != null) {
                if ("guest".equals(parentUser.getMode())) {
                    return error("You cannot bind guest");
                }
                VsUser user = new VsUser();
                user.setId(getLoginUser().getVsUser().getId());
                user.setParentUserId(vsUser.getId());
                int i = vsUserService.updateVsUser(user);
                if (i == 0) {
                    return error();
                }
                getLoginUser().getVsUser().setParentUserId(vsUser.getId());
                return success(i);
            } else {
                return error("The superior does not exist");
            }
        }
        return error("You have already bound your superior");
    }

    @PostMapping("/revokeUser")
    public AjaxResult revokeUser(@RequestBody VsUser vsUser) {
        int i = vsUserService.deleteVsUserById(getLoginUser().getVsUser().getId());
        VsDramasUserOauth oauth = new VsDramasUserOauth();
        oauth.setUserId(getLoginUser().getVsUser().getId());
        List<VsDramasUserOauth> oauths = vsDramasUserOauthService.selectVsDramasUserOauthList(oauth);
        if (oauths.size() > 0) {
            int id = vsDramasUserOauthService.deleteVsDramasUserOauthByUserId(getLoginUser().getVsUser().getId());
            i += id;
            if (i < 1) {
                return error();
            }
        }
        if (i < 0) {
            return error();
        }
        return success();
    }

}
